import type { AjaxRequestConfig, Data } from 'uni-ajax'
import type { Options, Response} from '@/hooks'
import type { ToastUtil, LoadingUtil } from '@/stores'

import ajax from 'uni-ajax'
import { useAppStore } from '@/stores'
import {FormObject} from "@/utils";

export const baseURL = 'https://tcyd.jianzhan580.com'
// export const baseURL = 'http://test.com'

// 创建请求实例
const request = ajax.create({
  // 初始配置
  baseURL,
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在发送请求前做些什么
    const token = uni.getStorageSync('token') || ''
    config.header.Authorization = token || ''
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    // 对响应数据做些什么
    return response.data
  },
  (error) => {
    // 对响应错误做些什么
    // console.log("error",error)
    // if (error)
    return Promise.reject(error)
  },
)

declare type Utils = {
  toast: ToastUtil,
  loading: LoadingUtil
}

export class AjaxRequest {
  toast: ToastUtil
  loading: LoadingUtil
  constructor(toast: ToastUtil, loading: LoadingUtil) {
    this.toast = toast
    this.loading = loading
  }

  private error(msg: string){
    this.toast.error(msg)
  }

  private startLoading(msg: string){
    this.loading.loading(msg)
  }

  private endLoading(){
    this.loading.close()
  }

  public send(method: string, url: string, data?: Data, options?: Options){
    const config: AjaxRequestConfig = { ...options?.config }
    return new Promise<Response>( (resolve, reject) => {
      const isLoading = options && Reflect.has(options, 'loading') && options.loading !== false
      if (isLoading) {
        let title = '提交中...'
        if (options?.loading && typeof options.loading == 'string') {
          title = options.loading
        }
        this.startLoading(title)
      }
      // @ts-ignore
      request[method](url, data, config).then((res) => {
        if (isLoading) { this.endLoading() }
        if (res.status) {
          resolve(res.data)
        } else {
          this.error(res.data.message)
          reject(res.data)
        }
      }).catch((error: any) => {
        if (isLoading) { this.endLoading()}
        if (error.statusCode === 401 || error.statusCode === 419) {
          this.error('请求授权失败!')
          uni.removeStorageSync('token')
          const appStore = useAppStore()
          if (appStore.getIsLogin()) {
            appStore.setIsLogin(false)
          }
        }else if (error.statusCode === 404) {
          this.error('请求URL资源地址不存在!')
        }else {
          this.error('网络请求失败!')
        }
        console.error('error',error)
        reject(error)
      })
    })
  }

  public get(url: string, data?: Data, options?: Options) {
    return this.send('get', url, data, options)
  }

  public post(url: string, data?: Data, options?: Options) {
    return this.send('post', url, data, options)
  }

  public put(url: string, data?: Data, options?: Options) {
    return this.send('put', url, data, options)
  }

  public delete(url: string, data?: Data, options?: Options) {
    return this.send('delete', url, data, options)
  }

  public formPost(url: string, data: Data, options?: Options) {
     const form = FormObject(data).getData()
     return this.send('post', url, form.buffer, {
      config: {
        header: {
          'Content-Type': form.contentType,
        },
        ...options?.config,
      },
      loading: options?.loading || false,
     })
  }

}



// 导出 create 创建后的实例
export {
  request,
}
